package com.globo.opensocial.tags;

import org.htmlparser.tags.CompositeTag;

import com.globo.opensocial.Parser;

public class ForTag extends CompositeTag {

    private static final String[] mIds = new String[]{"OSG:FOREACH"};

    public String[] getIds() {
        return (mIds);
    }

    /**
     * Return the set of tag names that cause this tag to finish.
     *
     * @return The names of following tags that stop further scanning.
     */
    public String[] getEnders() {
        return (mIds);
    }

    public boolean isValid() {
        return (getAttribute("itens") != null);

    }

    public String getKey() {
        return getAttribute("key");
    }

    public String getVar() {
        return getAttribute("var");
    }

    public void appendBegin(StringBuilder out, Parser parser) {
        if (!isValid()) {
            return;
        }

        String itens = getAttribute("itens");
        String var = getAttribute("var");
        String key = getAttribute("key");

        if (var == null) {
            var = "__1";
        }
        if (key == null) {
            key = "__2";
        }
        out.append("/*forEach*/\n");
        out.append(parser.getArrayToken(itens));
        out.append(".each( function(");
        out.append(var);
        out.append(", ");
        out.append(key);
        out.append(" ) { \n");
    }

    public void appendEnd(StringBuilder out) {
        if (!isValid()) {
            out.append("\n}); \n");
		}
	}
}